#include "./sensor.h"
#include "../../device/gpio.h"
#include "../../rtx/rtx_os.h"

namespace driver {

using namespace device::gpio;

uint16_t lastTim2Cnt = 0;
uint16_t stirSpeed = 0; 

using ICE_FULL = PB<3>;
using STIR_SPEED = PA<1>; // TIM2_CH2
using LEAK = PC<3>;
using BUCKET_HIGH = PC<4>;
using BUCKET_LOW = PC<5>;

Sensor::Sensor() {
    RCC->APB2ENR |= RCC_APB2ENR_IOPBEN |
        RCC_APB2ENR_IOPCEN |
        RCC_APB2ENR_IOPAEN;

    RCC->APB1ENR |= RCC_APB1ENR_TIM2EN | RCC_APB1ENR_TIM3EN;
    
    config_float_input<
        ICE_FULL, LEAK, BUCKET_HIGH, BUCKET_LOW,
        STIR_SPEED
    >();

    TIM2->CR1 = 0x00;
    TIM2->CR2 = 0x00;
    TIM2->SMCR = 0x67;
    TIM2->CCER = 0x0000;
    TIM2->CCMR1 = 0x0100;
    TIM2->CR1 = 0x01;

    // TIM3 每隔500ms测量 速度
    TIM3->CR1 = 0x00;
    TIM3->CR2 = 0x00;
    TIM3->PSC = 720 - 1;
    TIM3->ARR = 1000 * 50 - 1;
    TIM3->EGR = 0x01;
    TIM3->DIER = 0x01;
    TIM3->CR1 = 0x01;
    NVIC_EnableIRQ(TIM3_IRQn);
}

uint16_t Sensor::stir_speed() {
    return stirSpeed;
}

bool Sensor::is_ice_full() {
    return !ICE_FULL::read();
}

bool Sensor::is_bucket_high() {
    return BUCKET_HIGH::read();
}

bool Sensor::is_bucket_low() {
    return BUCKET_LOW::read();
}

bool Sensor::is_leak() {
    return LEAK::read();
}

}

using namespace driver;

extern "C"
void TIM3_IRQHandler() {
    if (TIM3->SR & TIM_SR_UIF) {
        TIM3->SR &= ~TIM_SR_UIF;
    }
    uint16_t cnt = TIM2->CNT;
    if (cnt < lastTim2Cnt) {
		stirSpeed = (cnt + 0xFFFF - lastTim2Cnt) * 2;
    } else {
        stirSpeed = (cnt - lastTim2Cnt) * 2;
    }
    lastTim2Cnt = cnt;
}

